<template>
  <div class="app-container calendar-list-container">
    <el-button class="filter-item" type="primary" @click="cancel">返回</el-button>
    <el-button class="filter-item" type="success" @click="addGoods">添加商品</el-button>
    <el-button class="filter-item" type="primary" @click="save">保存</el-button>
    <el-button class="filter-item" type="primary" @click="setAllPrice">批量设置单价</el-button>
    <div class="w-body">
      <el-form :model="entity" :rules="dataRule" ref="entity" label-width="80px" size="small">
        <el-row>
          <el-col :span="6">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="entity.customerName" :readonly="true">
                <el-button slot="append" icon="el-icon-search" @click="addCustomer"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="仓库列表" prop="warehouseCode">
              <el-select v-model="entity.warehouseCode" placeholder="请选仓库">
                <el-option v-for="(type,index) in warehouseList" :label="type.warehouseName" :value="type.warehouseCode" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="大货订单" prop="businessOrderNo">
              <el-input v-model="entity.businessOrderNo" :disabled="true">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="付款方式" prop="payType">
              <el-input v-model="entity.payType">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="运输方式" prop="transport">
              <el-input v-model="entity.transport">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="运输费用" prop="transportFee">
              <el-input v-model="entity.transportFee">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="币种" prop="currency">
              <el-select v-model="entity.currency" :disabled="view" placeholder="币种">
                <el-option v-for="(type,index) in currencyList" :label="type.name" :value="type.value" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否含税" prop="tax">
              <el-select v-model="entity.tax" placeholder="是否含税">
                <el-option v-for="(type,index) in yesOrNo" :label="type.name" :value="type.value" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="" prop="remark">
              <quill-editor v-model="entity.remark" ref="quillEditor" style="height:300px" :options="{ modules:{ toolbar:[ ['bold', 'italic', 'underline', 'strike']]}}">
              </quill-editor>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="">
              <div class="w-table">
                <grid gridTitle="物品信息" :columns="columns" :enableEdit="true" :loading="false" ref="mainGrid" height="400" :pagination="false" @delete="doDelete"
                  :permissions="permissions" :keyEditStep="2"></grid>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件">
              <el-upload class="upload-demo" :action="uplaodFileUrl" :on-success="fileSuccess" :on-remove="fileRemove" :file-list="fileList" accept="image/*">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <GridDialog ref="customerGridDialog" :url="customerUrl" :columns="customerColumns" @select="selectCustomerData" :permissions="permissions" :queryEntity="customerQueryList">
    </GridDialog>
    <GridDialog ref="goodsGridDialog" :multi="true" :url="goodsUrl" :columns="goodsColumns" @select="selectGoodsData" :permissions="permissions" :queryEntity="goodsQueryEntity"
      :queryList="modelQueryList">
    </GridDialog>

  </div>
</template>

<script>
import request from '@/router/axios'
import { Message, MessageBox } from 'element-ui'
import url from '@/const/apiURL'
import GridDialog from '@/components/GridDialog'
import grid from '@/components/Grid'
import { mapGetters } from 'vuex'
import { queryField } from '@/const/query'
import { dict } from '@/const/dict'
import { colunms } from '@/const/colunms'


export default {
  components: { GridDialog, grid },
  data () {
    return {
      customerQueryEntity: { customerType: 'SUPPLIER' },
      goodsQueryEntity: { businessOrderNo: null },
      uplaodFileUrl: url.UPLOAD_FILE_URL,
      fileList: [],
      currencyList: dict().Currency,
      yesOrNo: dict().YesOrNo,
      warehouseList: [],
      customerUrl: url.CUSTOMER_LIST_URL,
      goodsUrl: url.PURCHASE_ALL_GOODS_LIST_URL,
      orderQueryList: queryField().order,
      modelQueryList: queryField().modelName,
      orderNo: '',
      entity: {
        businessOrderNo: '',
        customerCode: '',
        customerName: '',
        goods: [],
        files: []
      },
      columns: [
        { label: this.global.modelName, width: 120, prop: 'goodsName', align: 'left' },
        { label: this.global.modelProp, width: 100, prop: 'modelProp', align: 'left' },
        { label: '物料名称', width: 180, prop: 'materialName', align: 'left' },
        { label: '物料类型', width: 100, prop: 'materialTypeName', align: 'center' },
        { label: '单位', width: 80, prop: 'unit', align: 'center' },
        { label: '需要数量', width: 80, prop: 'needQuantity', align: 'center' },
        { label: '已采购数量', width: 100, prop: 'purchaseQuantity', align: 'center' },
        // { label: '序列号', width: 160, prop: 'serialNumber', align: 'center', template: 'edit', type: 'text' },
        //   { label: '批次号', width: 180, prop: 'batchNo', align: 'center', template: 'edit', type: 'text' },
        { label: '单价', width: 120, prop: 'price', align: 'center', template: 'edit', type: 'number' },
        { label: '数量', width: 120, prop: 'quantity', align: 'center', template: 'edit', type: 'number' },
        { label: '操作', width: 80, prop: 'op', align: 'center', template: 'op', opList: [{ name: '删除', clickName: 'delete', auth: 'yes' }] }
      ],
      goodsColumns: colunms().modelColumns,
      customerColumns: colunms().customerColumns,
      orderColumns: colunms().orderColumns,
      dataRule: {
        customerName: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
        warehouseCode: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
        currency: [{ required: true, message: '币种不能为空', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.orderNo = this.$route.query.orderNo
    this.entity.businessOrderNo = this.$route.query.businessOrderNo
    this.goodsQueryEntity.businessOrderNo = this.entity.businessOrderNo
    this.init()
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  methods: {
    init () {
      this.initWarehouse()
      this.initData()
    },
    cancel () {
      this.$router.push({ path: '/prod/purchase', query: {} })
    },
    setAllPrice () {
      MessageBox.prompt('', '请输入单价', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((data) => {
        this.$refs['mainGrid'].getData().forEach(row => {
          row.price = Number(data.value)
        })
      })
    },
    fileSuccess (data) {
      if (data.success) {
        let file = data.data
        this.entity.files.push({ fileName: file.fileName, fileUrl: file.url })
      } else {
        MessageBox.alert(data.msg)
      }
    },
    fileRemove (file, fileList) {
      this.entity.files = []
      if (fileList) {
        fileList.forEach(f => {
          this.entity.files.push({ fileName: f.name, fileUrl: f.response.data.url })
        });
      }
    },
    initData () {
      this.viewUrl(this.orderNo).then(data => {
        if (data) {
          this.entity = data
          data.goods.forEach(row => {
            this.$refs['mainGrid'].addRow(row)
          })
          data.files.forEach(row => {
            this.fileList.push({ name: row.fileName, response: { data: { url: row.fileUrl } } })
          })
        }
      })
    },
    openOrder () {
      this.$refs['orderGridDialog'].show()
    },
    selectOrderData (row) {
      this.entity.businessOrderNo = row.orderNo
    },
    addCustomer () {
      this.$refs['customerGridDialog'].show()
    },
    selectCustomerData (row) {
      this.entity.customerName = row.customerName
      this.entity.customerCode = row.customerCode
    },
    addGoods () {
      this.$refs['goodsGridDialog'].show()
    },
    selectGoodsData (rows) {
      rows.forEach(row => {
        const rowData = {
          goodsCode: row.modelCode,
          modelName: row.modelName,
          materialName: row.materialName,
          materialTypeName: row.materialTypeName,
          unit: row.unit,
          modelProp: row.modelProp,
          needQuantity: row.quantity,
          purchaseQuantity: row.finishQuantity,
          quantity: row.quantity || 0,
          price: 0,
          batchNo: '',
          serialNumber: ''
        }
        this.$refs['mainGrid'].addRow(rowData)
      })
    },
    save () {
      if (this.entity.warehouseCode) {
        let purchase = this.entity
        purchase.goods = this.$refs['mainGrid'].getData()
        this.saveUrl(purchase).then(data => {
          if (data) {
            this.$router.push({ path: '/prod/purchase', query: {} })
          }
        })
      } else {
        MessageBox.alert("请选择仓库")
      }
    },
    doDelete (row) {
      this.$refs['mainGrid'].deleteRow(row)
    },
    initWarehouse () {
      this.warehouseUrl().then(data => {
        if (data) {
          this.warehouseList = data
        }
      })
    },
    viewUrl (orderNo) {
      return request({
        url: url.PURCHASE_VIEW_URL,
        method: 'post',
        data: { key: 'key' },
        params: { orderNo }
      })
    },
    saveUrl (data) {
      return request({
        url: url.PURCHASE_EDIT_URL,
        method: 'post',
        data: data
      })
    },
    warehouseUrl () {
      return request({
        url: url.WAREHOUSE_USABLE_URL,
        method: 'post',
        data: { key: 'key' }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.w-body {
  padding-top: 8px;
}
.w-table {
  border: 1px solid #ebeef5;
  margin-top: 50px;
}
.w-table-title {
  border: 1px solid #ebeef5;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
  line-height: 23px;
  display: inline-block;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  position: relative;
  vertical-align: middle;
  width: 100%;
  font-size: 14px;
  color: gray;
}
</style>
